from django.shortcuts import render,HttpResponse

from stu_exam_manage.models import Lilun_title, Lilun_unit_name

import os
import re
import json
from bs4 import BeautifulSoup


#  ********* html网页理论题配置 **********

course_id = 2   # ** 必填 ** 请查询Course表查看课程对应的课程id
path_lilun_html_path = r'C:\inetpub\wwwroot\students_study_sys\stu_exam_manage\utils\all_lilun_html_titles'  # 存放理论网页的路径  ** 一般必填 **
course = r'大数据深度学习'     # 当前课程  ** 一般必填 **

re_pattern = course + r'.+html'     # 匹配所有网页数据


# Create your views here.
# 将所有的网页版理论题写入数据库
def writeToDB(htmlpath):
    '''
    将所有的理论题写入数据库
    :param htmlpath: 所有html理论题的html路径
    :return: None
    '''

    with open(htmlpath, 'rb') as fr:
        soup = BeautifulSoup(fr.read(), 'html.parser')
        li_titles = soup.select('#exampaper-body > li')

        # print( '-------', soup.select_one('#name')['value'])   # 110 测试
        basename = os.path.basename(htmlpath)  # 获取文件名
        kaoti = Lilun_unit_name(name=basename, course_id=course_id)
        kaoti.save()
        for li in li_titles:
            try:
                # print(li.select_one('div.answer-desc > div.answer-desc-summary > span.answer_value')),    # 110测试
                # print(li.select_one('div.answer-desc > div:nth-of-type(2) > div > span:nth-of-type(2)')), # 110测试
                Lilun_title(
                    bianhao = int(li.select_one('.question-no').string[:-1]),
                    kaoti = kaoti,
                    zhishidian = '缺省知识点',
                    leixing    = '00' + li.select_one('div.question-title > span:nth-of-type(3)').string[1:-2],
                    tigan      = li.select_one('div.question-body > pre').string,
                    xxa        = xxselect(li.select_one('div.question-body > ul > li:nth-of-type(1) > span')),
                    xxb        = xxselect(li.select_one('div.question-body > ul > li:nth-of-type(2) > span')),
                    xxc        = xxselect(li.select_one('div.question-body > ul > li:nth-of-type(3) > span')),
                    xxd        = xxselect(li.select_one('div.question-body > ul > li:nth-of-type(4) > span')),
                    xxe        = xxselect(li.select_one('div.question-body > ul > li:nth-of-type(5) > span')),
                    xxf        = xxselect(li.select_one('div.question-body > ul > li:nth-of-type(6) > span')),
                    daan       = judgeUpdate(li.select_one('div.answer-desc > div.answer-desc-summary > span.answer_value').string.strip()),
                    jiexi      = '',
                    chutiren   = '',
                ).save()

            except Exception as e:
                print('报错信息：',e)
    print('read success')


# 选项处理
def xxselect(soupContent):
    if soupContent:
        return soupContent.string[2:].strip()
    else:
        return ''

#  Update answer for judge
def judgeUpdate(strs):
    if strs == '对':
        return 'A'
    elif strs == '错' :
        return 'B'
    else:
        return strs


# 获取所有存放html文件的路径
def query(path):
    '''
    # 获取所有存放html文件的路径
    :param path:  存放html文件的文件夹路径
    :return:    返回所有的html文件的路径
    '''

    all_html_paths = []
    for i in os.walk(path):
        print(i)
        if len(i[1]) == 0:
            for j in i[2]:
                # print(j)
                if re.match(re_pattern, j.strip()):
                    all_html_paths.append(os.path.join(i[0], j))
    print('所有需要保存的html网页路径：', len(all_html_paths))    # 110测试
    print(re_pattern)
    for i in all_html_paths:
        print(i)

    for i in all_html_paths:
        print('正在运行：',i)    # 110
        writeToDB(i)


# 保存网页版理论题目的入口
def save_new_html_liluntitles(request):
    '''
    保存理论题目的入口
    :param request: django服务器调用url请求
    :return:    None
    '''

    #  自定义理论题目文件夹路径
    path = path_lilun_html_path
    query(path)     # 进入保存模式

    return HttpResponse('保存理论题目成功')


# 清空所有的理论题表以及理论题目表
def delete_all_html_liluntitles(request):
    '''
    清空所有的理论题表以及理论题目表
    :param request:
    :return:
    '''
    try:
        Lilun_title.objects.filter(kaoti__course_id=2).delete()
        Lilun_unit_name.objects.filter(course_id=2).delete()
        # print(Lilun_title.objects.filter(kaoti__course_id=2))
        # print(type(Lilun_unit_name.objects.filter(course_id=2)))
        # for i in Lilun_unit_name.objects.filter(id__gt=326):
        #     i.lilun_title_set.all().delete()
        #     i.delete()
    except Exception as e:
        return HttpResponse('清空理论题目表和理论试卷表---》失败')

    return HttpResponse('已经为您清空理论题目表和理论试卷表--》成功')